import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index.js' // 1. 引入用户仓库
import { ElMessage } from 'element-plus'
import { filterRoute } from '@/utils/renderRoute.js'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/Index.vue')
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('../views/404/404.vue')
    },
    {
      path: '/',
      name: 'layout',
      meta: {
        title: '主页',
        icon: 'house'
      },
      component: () => import('../views/layout/Index.vue')
    }
  ]
})
let hasInitAuth = true
const writeLists = ['login']
// 登录访问拦截
router.beforeEach(async (to, from) => {
  document.title = to.meta?.title || '后台管理系统'
  if (writeLists.includes(to.name)) {
    return
  }
  const userStore = useUserStore()
  if (to.matched.length === 0 && userStore.getToken()) {
    if (from.name) {
      console.log('返回原来路由')
      return { name: from.name }
    } else {
      console.log('没有匹配到路由')
      return '/'
    }
  } else {
    if (to.path !== '/login' && !userStore.getToken()) {
      ElMessage({
        message: '账号未登录或登录到期，请重新登录',
        type: 'error'
      })
      return '/login'
    }
  }
  if (hasInitAuth) {
    console.log('初始化路由')
    hasInitAuth = false
    const routerList = filterRoute(userStore.getMenus())
    userStore.setRoutesList(routerList)
    return { ...to, replace: true }
  }
})

export default router
